package com.me.mvc.controller;

import com.me.mvc.model.ModelUtils;
import com.me.mvc.model.entity.*;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

/**
 * @author Roman Uholnikov
 */
@Controller
@RequestMapping(value = "/accounts")
public class Accounts {

    @RequestMapping(method = RequestMethod.GET)
    public String showForm(ModelMap model) {
        model.addAttribute("account", new Account(ModelUtils.accountMap.size() +1 ));
        model.addAttribute("accounts",ModelUtils.accountMap.values());
        return "accounts";
    }

    @RequestMapping(method = RequestMethod.POST)
    public String showForm(ModelMap model, @ModelAttribute("accountForm") Account accountForm, BindingResult result) {
        if(!result.hasErrors()) {
            ModelUtils.accountMap.put(accountForm.getId(), accountForm);
        }
        return "accounts";

    }

    @RequestMapping(value = "/{accountId}",method = RequestMethod.GET)
    public String showFormGet(ModelMap model, @PathVariable("accountId") Integer accaountId,  @ModelAttribute("accountForm") Account accountForm, BindingResult result) {
        model.addAttribute("accountForm", ModelUtils.accountMap.get(accaountId));
        model.addAttribute("mapOfClients", ModelUtils.clientMap);
        model.addAttribute("mapOfBanks", ModelUtils.bankMap);
        return "account";
    }

    @RequestMapping(value = "/{accountId}",method = RequestMethod.POST)
    public String showFormPost(ModelMap model, @PathVariable("accountId") Integer accountId, @ModelAttribute("accountForm") Account accountForm, BindingResult result) {
        if(!result.hasErrors()) {
            Account account = accountForm;
            account.setClient(ModelUtils.clientMap.get(accountForm.getClient().getId()));
            account.setBank(ModelUtils.bankMap.get(accountForm.getBank().getId()));
            ModelUtils.accountMap.put(accountForm.getId(), accountForm);
            return "redirect:/accounts";
        }
        return "account";
    }
}
